package com.ikas.ai.server.module.system.controller;

import com.alibaba.druid.util.Base64;
import com.ikas.ai.consts.Consts;
import com.ikas.ai.handle.JsonResult;
import com.ikas.ai.handle.JsonResultType;
import com.ikas.ai.server.module.system.service.CaptchaService;
import com.ikas.ai.utils.GuidUtil;
import com.ikas.ai.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 验证码接口
 */
@Validated
@RestController
@RequestMapping
public class CaptchaController {

    @Autowired
    private CaptchaService captchaService;
    @Autowired
    private RedisUtil redisUtil;


    /**
     * 获取登录失败次数
     *
     * @return
     */
    @GetMapping("/login/{userName}")
    public String loginFail(@PathVariable("userName") @NotEmpty(message = "请输入合法用户名") String userName) {
        Integer count = redisUtil.getBean(Consts.PREFIX_USER_LOGIN + userName,Integer.class);
        JsonResult jsonResult = new JsonResult(JsonResultType.OK);
        jsonResult.add(count == null ? 0 : count.intValue());
        return jsonResult.toJSON();
    }

    /**
     * 获取验证码
     *
     * @return
     */
    @GetMapping("/captcha")
    public String captcha(HttpServletResponse response) {
        JsonResult jsonResult = new JsonResult(JsonResultType.OK);
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        //生成redis的唯一key,用于存储验证码的值
        String uuid = GuidUtil.getId();
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //获取图片验证码
        BufferedImage image = captchaService.getCaptcha(uuid);
        //输出图片流 直接返回图片给前端
        try {
            //将绘制得图片输出到流
            ImageIO.write(image, "png", bs);
            String base64Img = Base64.byteArrayToBase64(bs.toByteArray());
            jsonResult.setMessage("获取验证码成功");
            jsonResult.add("uuid", uuid);
            jsonResult.add("captcha", "data:image/gif;base64," + base64Img);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bs.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (bs != null) {
                    bs = null;
                }
            }
        }
        return jsonResult.toJSON();
    }

}
